package lanou.a36ke_01.tools;

import android.os.Handler;
import android.os.Looper;

import com.litesuits.orm.LiteOrm;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lanou.a36ke_01.beanlists.newsbean.NativeBean;

/**
 * <p>
 * 数据库的操作类
 * 使用单例模式,因为LiteOrm要求
 * 其他数据库框架 GreenDao,OrmLite
 */
public class DBTool {
    //liteOrm 对象,曾删改查方法 都操作此对象
    private LiteOrm mLiteOrm;
    //Handler 用来做线程切换,为了在主线程来执行回调,返回数据
    private Handler mHandler;

    //线程池
    ExecutorService threadPool = Executors.newFixedThreadPool(5);


    private static DBTool ourInstance = new DBTool();

    public static DBTool getInstance() {
        return ourInstance;
    }


    public DBTool() {
        //初始化liteOrm对象
        //使用MyApp里的全局Context
        //第二个参数是 数据库的名字
        mLiteOrm = LiteOrm.newSingleInstance(MyApp.getContext(), "My.db");
        //初始化Handler
        //Handler的构造方法 参数如果传
        // Looper.getMainLooper()
        // 代表这个Handler 一定会回调到主线程
        // 属于严谨的写法

        mHandler = new Handler(Looper.getMainLooper());

    }

    //去重复
    private boolean hasNativeBean(NativeBean nativeBean) {
        ArrayList<NativeBean> query = mLiteOrm.query(NativeBean.class);
        for (NativeBean nativeList : query) {
            if (nativeList.getUrl().equals(nativeBean.getUrl())) {
                return true;
            }
        }
        return false;
    }
    //向数据库插入一个用户

    public void insertUser(final NativeBean nativeBean) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
//                if (!hasNativeBean(nativeBean)) {
                    mLiteOrm.insert(nativeBean);
//                }
            }
        });

    }

    //查询用户名的方法

    public void queryUesr(final QueryListener queryListener) {

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                ArrayList<NativeBean> nativeBeen = mLiteOrm.query(NativeBean.class);

                mHandler.post(new HandlerRunnable(nativeBeen, queryListener));
            }
        });


    }

    class HandlerRunnable implements Runnable {
        ArrayList<NativeBean> nativeBeens;
        QueryListener mQueryListener;
        //构造方法
        public HandlerRunnable(ArrayList<NativeBean> nativeBeen, QueryListener queryListener) {
            nativeBeens = nativeBeen;
            mQueryListener = queryListener;
        }

        @Override
        public void run() {
            mQueryListener.onQueryComplete(nativeBeens);
        }
    }

    public interface QueryListener {
        void onQueryComplete(ArrayList<NativeBean> nativeBeen);
    }

}

